<?php

namespace app\api\service;

use app\common\model\Order;
use app\common\model\OrderItem;
use app\common\model\user\Artwork;
use app\common\model\user\ArtworkAttribute;

class ArtworkService extends BaseService
{

    public function submitOrder(Artwork $artwork, $userId)
    {
        $discountAmount = 0;
        $content = '';
        $remark = '';
        $qty = 1;

        $artworkAttribute = ArtworkAttribute::with([
            'product',
            'fbx',
        ])->where([
            'artwork_id' => $artwork['id'],
        ])->select();
        if (empty($artworkAttribute)) {
            $this->setMsg('找不到相关的作品属性');
            return false;
        }

        $snapshot = Artwork::genSnapshot($artwork['id'], $artwork['version']);

        $price = 0;
        foreach ($artworkAttribute as $art) {
            $product = $art->product;
            $price = bcadd($price, $product['price'], 2);

        }

        $amount = bcmul($price, $qty, 2);
        $order = new OrderService();

        $orderRes = $order->submit(Order::TYPE_ARTWORK, $userId, $amount, $discountAmount);
        if (empty($orderRes)) {
            $this->setMsg($order->getMsg());
            return false;
        }

        $orderItem = new OrderItemService();
        $resItem = $orderItem->submit($orderRes->id, $snapshot['id'], OrderItem::DATA_TYPE_ARTWORK, $snapshot['name'], $qty, $price, $discountAmount, $content, $remark);
        if (empty($resItem)) {
            $this->setMsg($orderItem->getMsg());
            return false;
        }
        $orderRes['order_item'] = $resItem;
        foreach ($artworkAttribute as $art) {

            $orderItem1 = new OrderItemService();
            $resItem1 = $orderItem1->submit($orderRes->id, $art->product['id'], OrderItem::DATA_TYPE_PRODUCT, $art->product['name'], $qty, $art->product['price'], $discountAmount, $content, $remark);
            if (empty($resItem1)) {
                $this->setMsg($orderItem1->getMsg());
                return false;
            }

        }

        return $orderRes;
    }
}